# 用户路由
from flask import request, jsonify, g
from models import User, db, Dataset, Model, Predict, Plant
from utils.password_utils import encode_password, check_password


def register_user_routes(app):
    # 查询所有用户
    @app.route('/plantACR/getUsers', methods=['GET'])
    def get_users():
        # 定义 resultVO，包含code和data的字典，用于存储响应信息
        resultVO = {
            "code": 200,
            "data": {
                "users": []
            }
        }
        try:
            # 按id升序排序
            users_asc = User.query.order_by(User.id.asc()).all()
            if users_asc:
                for user in users_asc:
                    user_info = {
                        "id": user.id,
                        "name": user.name,
                        "role": user.role,
                        "create_time": user.create_time
                    }
                    resultVO["data"]["users"].append(user_info)
                return jsonify(resultVO)
            else:
                # 不需要设定code为404，因为表空，那么前端只需要渲染空的表格即可
                # resultVO["code"] = 404
                resultVO["message"] = '用户列表为空'
                return jsonify(resultVO)
        except Exception as e:
            resultVO["code"] = 500
            resultVO["message"] = "服务器异常，获取用户列表失败！" + str(e)
            return jsonify(resultVO)

    # 注册用户
    @app.route('/plantACR/createUser', methods=['POST'])
    def create_user():
        # 定义 resultVO，包含code和data的字典，用于存储响应信息
        resultVO = {
            "code": 200,
            "data": {}
        }
        try:
            data = request.get_json()
            name = data.get('name')
            password = data.get('password')

            # 检查用户名是否已存在
            existing_user = User.query.filter_by(name=name).first()
            if existing_user:
                resultVO["code"] = 400
                resultVO["message"] = '用户名已存在'
                return jsonify(resultVO)

            # 对密码进行加密
            hashed_password = encode_password(password)

            # 创建新用户
            new_user = User(name=name, password=hashed_password, role='user')
            db.session.add(new_user)
            db.session.commit()
            resultVO["message"] = '用户创建成功'
            # 刚刚创建的用户信息
            resultVO["data"] = {
                "role": new_user.role,
                "user": {
                    "id": new_user.id,
                    "name": new_user.name,
                    "role": new_user.role,
                    "create_time": new_user.create_time,
                    "update_time": new_user.update_time
                }
            }
            return jsonify(resultVO)
        except Exception as e:
            db.session.rollback()
            # 处理异常，返回500错误
            resultVO["code"] = 500
            resultVO["message"] = "服务器异常，用户创建失败！" + str(e)
            return jsonify(resultVO)

    # 注册管理员
    @app.route('/plantACR/createAdmin', methods=['POST'])
    def create_admin():
        resultVO = {
            "code": 200,
            "data": {}
        }
        try:
            # 验证当前用户是否为 superAdmin
            if g.role != 'superAdmin':
                resultVO["code"] = 403
                resultVO["message"] = '权限不足，只有超级管理员可以创建管理员'
                return jsonify(resultVO)

            data = request.get_json()
            name = data.get('name')
            password = data.get('password')

            # 检查用户名是否已存在
            existing_user = User.query.filter_by(name=name).first()
            if existing_user:
                resultVO["code"] = 400
                resultVO["message"] = '用户名已存在'
                return jsonify(resultVO)

            # 对密码进行加密
            hashed_password = encode_password(password)

            # 创建新管理员
            new_admin = User(name=name, password=hashed_password, role='admin')
            db.session.add(new_admin)
            db.session.commit()

            resultVO["message"] = '管理员创建成功'
            resultVO["data"] = {
                "role": new_admin.role,
                "user": {
                    "id": new_admin.id,
                    "name": new_admin.name,
                    "password": new_admin.password,
                    "role": new_admin.role,
                    "create_time": new_admin.create_time,
                    "update_time": new_admin.update_time
                }
            }
            return jsonify(resultVO)
        except Exception as e:
            db.session.rollback()
            resultVO["code"] = 500
            resultVO["message"] = "服务器异常，管理员创建失败！" + str(e)
            return jsonify(resultVO)

    # 更新用户
    @app.route('/plantACR/updateUser', methods=['POST'])
    def update_user():
        # 定义 resultVO，包含code和data的字典，用于存储响应信息
        resultVO = {
            "code": 200,
            "data": {}
        }
        try:
            # 获取当前登录用户的id和role
            current_user_id = g.id
            current_user_role = g.role

            data = request.get_json()
            print("数据：", data)
            user_id = data.get('id')
            new_name = data.get('name')

            # 检查当前登录用户是否为admin 或 id是否为自己的id
            if current_user_role != 'admin' and current_user_id != user_id:
                resultVO["code"] = 403
                resultVO["message"] = '权限不足'
                return jsonify(resultVO)

            # 检查新用户名是否已存在
            existing_user = User.query.filter_by(name=new_name).first()
            if existing_user:
                resultVO["code"] = 400
                resultVO["message"] = '要更新的用户名已存在'
                return jsonify(resultVO)

            user = User.query.get(user_id)

            if user:
                # 更新信息，如果请求中没有提供某个字段的值，则使用用户当前的值
                user.name = data.get('name', user.name)
                db.session.commit()

                # 与用户关联的所有数据集的user_name字段更新为新的user_name
                datasets = Dataset.query.filter_by(user_id=user.id).all()
                if datasets:
                    for dataset in datasets:
                        dataset.user_name = user.name
                        db.session.commit()

                resultVO["data"] = {
                    "role": user.role,
                    "user": {
                        "id": user.id,
                        "name": user.name,
                        "role": user.role,
                        "create_time": user.create_time,
                        "update_time": user.update_time
                    }
                }
                resultVO["message"] = '用户更新成功'
                return jsonify(resultVO)
            else:
                resultVO["code"] = 404
                resultVO["message"] = '用户不存在'
                return jsonify(resultVO)
        except Exception as e:
            db.session.rollback()
            resultVO["code"] = 500
            resultVO["message"] = "服务器异常，用户更新失败！" + str(e)
            return jsonify(resultVO)

    # 重置用户密码
    @app.route('/plantACR/resetPassword', methods=['POST'])
    def reset_password():
        # 定义 resultVO，包含 code 和 data 的字典，用于存储响应信息
        resultVO = {
            "code": 200,
            "data": {}
        }
        try:
            # 获取当前登录用户的 role
            current_user_role = g.role

            data = request.get_json()
            user_id = data.get('id')

            # 检查当前登录用户是否为 管理员
            if current_user_role != 'admin':
                resultVO["code"] = 403
                resultVO["message"] = '权限不足'
                return jsonify(resultVO)

            user = User.query.get(user_id)

            if user:
                # 重置密码为 123456 的加密结果
                new_password = '$2b$12$lZUKtWBtDPvQfVjiA3LoOOMiq/bkZYfJFsOkZvA3.0ofD0wXk/jWm'
                user.password = new_password
                db.session.commit()
                resultVO["data"] = {
                    "user": {
                        "id": user.id,
                        "name": user.name
                    }
                }
                resultVO["message"] = '用户密码重置成功'
                return jsonify(resultVO)
            else:
                resultVO["code"] = 404
                resultVO["message"] = '用户不存在'
                return jsonify(resultVO)
        except Exception as e:
            db.session.rollback()
            resultVO["code"] = 500
            resultVO["message"] = "服务器异常，用户密码重置失败！" + str(e)
            return jsonify(resultVO)

    # 注销用户
    @app.route('/plantACR/deleteUser', methods=['POST'])
    def delete_user():
        resultVO = {
            "code": 200,
            "data": {}
        }
        try:
            current_user_role = g.role

            data = request.get_json()
            user_id = data.get('id')

            # 检查权限，只有管理员能注销用户
            if current_user_role != 'admin':
                resultVO["code"] = 403
                resultVO["message"] = '权限不足'
                return jsonify(resultVO)

            # 检查用户是否存在数据集
            user_datasets = Dataset.query.filter_by(user_id=user_id).first()
            if user_datasets:
                resultVO["code"] = 400
                resultVO["message"] = '该用户存在数据集，无法注销'
                return jsonify(resultVO)

            # 检查用户是否存在模型
            user_models = Model.query.filter_by(user_id=user_id).first()
            if user_models:
                resultVO["code"] = 400
                resultVO["message"] = '该用户存在模型，无法注销'
                return jsonify(resultVO)

            # 检查用户是否存在预测记录
            user_predicts = Predict.query.filter_by(user_id=user_id).first()
            if user_predicts:
                resultVO["code"] = 400
                resultVO["message"] = '该用户存在预测记录，无法注销'
                return jsonify(resultVO)

            user = User.query.get(user_id)
            if user:
                db.session.delete(user)
                db.session.commit()
                resultVO["data"] = {
                    "user": {
                        "id": user.id,
                        "name": user.name
                    }
                }
                resultVO["message"] = '用户注销成功'
                return jsonify(resultVO)
            else:
                resultVO["code"] = 404
                resultVO["message"] = '用户不存在'
                return jsonify(resultVO)
        except Exception as e:
            db.session.rollback()
            resultVO["code"] = 500
            resultVO["message"] = "服务器异常，用户注销失败！" + str(e)
            return jsonify(resultVO)

    # 获取全局统计信息
    @app.route('/plantACR/getHomeInfo', methods=['GET'])
    def get_home_info():
        resultVO = {
            "code": 200,
            "data": {
                "home_info": {
                    "user_count": 0,
                    "plant_count": 0,
                    "dataset_count": 0,
                    "model_count": 0,
                    "predict_count": 0
                }
            }
        }
        try:
            resultVO["data"] = {
                "home_info": {
                    "user_count": User.query.count(),
                    "plant_count": Plant.query.count(),
                    "dataset_count": Dataset.query.count(),
                    "model_count": Model.query.count(),
                    "predict_count": Predict.query.count()
                }
            }
            return jsonify(resultVO)
        except Exception as e:
            print("错误：", str(e))
            resultVO["code"] = 500
            resultVO["message"] = "服务器异常，获取主页统计信息失败！"
            return jsonify(resultVO)

    # 获取当前用户统计信息
    @app.route('/plantACR/getUserInfo', methods=['GET'])
    def get_user_infos():
        resultVO = {
            "code": 200,
            "data": {
                "user_info": {
                    "id": 0,
                    "name": "",
                    "role": "",
                    "create_time": "",
                    "plant_count": 0,
                    "dataset_count": 0,
                    "model_count": 0,
                    "predict_count": 0,
                    "dataset_process": 0,
                    "model_process": 0,
                    "predict_process": 0
                }
            }
        }
        try:
            current_user_id = g.id
            user = User.query.get(current_user_id)
            if not user:
                resultVO["code"] = 404
                resultVO["message"] = '用户不存在'
                return jsonify(resultVO)

            # 获取用户相关的所有植物ID（去重）
            dataset_plants = set(d.plant_id for d in Dataset.query.filter_by(user_id=current_user_id).all())
            model_plants = set(m.plant_id for m in Model.query.filter_by(user_id=current_user_id).all())
            predict_plants = set(p.plant_id for p in Predict.query.filter_by(user_id=current_user_id).all())
            unique_plants = dataset_plants.union(model_plants).union(predict_plants)

            resultVO["data"]["user_info"] = {
                "id": user.id,
                "name": user.name,
                "role": user.role,
                "create_time": user.create_time,
                "plant_count": len(unique_plants),
                "dataset_count": Dataset.query.filter_by(user_id=current_user_id).count(),
                "model_count": Model.query.filter_by(user_id=current_user_id).count(),
                "predict_count": Predict.query.filter_by(user_id=current_user_id).count(),
                "dataset_process": Dataset.query.filter_by(user_id=current_user_id, status='处理中').count(),
                "model_process": Model.query.filter_by(user_id=current_user_id, status='训练中').count(),
                "predict_process": Predict.query.filter_by(user_id=current_user_id, status='预测中').count()
            }
            return jsonify(resultVO)
        except Exception as e:
            print("错误：", str(e))
            resultVO["code"] = 500
            resultVO["message"] = "服务器异常，获取用户统计信息失败！"
            return jsonify(resultVO)

    # 更新用户密码
    @app.route('/plantACR/updatePassword', methods=['POST'])
    def update_password():
        resultVO = {
            "code": 200,
            "data": {}
        }
        try:
            data = request.get_json()
            old_password = data.get('old_password')
            new_password = data.get('new_password')
            user = User.query.get(g.id)
            if not user:
                resultVO["code"] = 404
                resultVO["message"] = '用户不存在'
                return jsonify(resultVO)
            if not check_password(old_password, user.password):
                resultVO["code"] = 400
                resultVO["message"] = '原密码输入错误'
                return jsonify(resultVO)
            user.password = encode_password(new_password)
            db.session.commit()
            resultVO["data"] = {
                "user": {
                    "id": user.id,
                    "name": user.name
                }
            }
            resultVO["message"] = '密码修改成功'
            return jsonify(resultVO)
        except Exception as e:
            db.session.rollback()
            print("错误：", str(e))
            resultVO["code"] = 500
            resultVO["message"] = "服务器异常，密码修改失败！"
            return jsonify(resultVO)

    return app
